#!/usr/bin/python
# -*- coding: utf8 -*-
#
# No Python 3 while poppler arrive
#

import os
import sys

if __name__ == "__main__":
    currentdir = os.path.dirname( os.path.abspath( sys.argv[0] ) )
    basedir = os.path.abspath( os.path.join( currentdir, ".." ) )
    pythondir = basedir
    sys.path.insert( 0, pythondir )

def launch():

    from argparse import ArgumentParser
    from logger import get_file_logger

    log = get_file_logger("extract-tool")

    try:
        parser = ArgumentParser(description='Run image archive extraction tool.')
        parser.add_argument('--archive', dest='archive', action='store', type=str,
            help='Archive file name')
        parser.add_argument('--mime', dest='mime', action='store', type=str,
            help='Archive file MIME')
        parser.add_argument('--into-dir', dest='into_dir', action='store', type=str,
            help='Extract into directory')

        args = parser.parse_args()

        from archive import Archive

        log.debug("Extract Tool: archive=%r, mime=%r" % (args.archive, args.mime,))

        arch = Archive(args.archive, args.mime)

        files = arch.get_files()

        log.debug("-- files count=%r" % (len(files),))
        # log.debug("Extract Tool: files=%r" % (files,))

        images_count = 0
        has_image = False
        for name in files:
            name = name.lower()
            ext = name.split(".")[-1]
            if ext in ("jpg", "jpeg", "jpe", "png", "gif", "bmp"):
                has_image = True
                images_count += 1

        log.debug("-- images count=%r" % (images_count,))

        if has_image and arch.extract_files(args.into_dir):
            log.debug("-- has images and extracted")
            return 0
        log.debug("-- no images here...")
    except Exception as e:
        log.error(e)
    return 1

if __name__ == "__main__":
    sys.exit(launch())
